package com.gaga.console;

import cn.hutool.core.thread.ThreadUtil;
import com.gaga.common.exception.BusException;
import com.gaga.console.core.entity.dto.ConfigDto;
import com.gaga.console.core.service.AssistantService;
import com.gaga.console.core.service.BvAudioPlayService;
import com.gaga.console.core.service.BvConfigService;
import com.gaga.console.core.service.BvModelService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 主要验证2个层面
 * 1、启动的时候需要去检查winning.executor.port是否被占用，如果被占用，不要启动整个服务
 * 2、验证license，目前还没有实现这部分代码
 *
 * @author lenovo
 * @description: 启动应用之前的一些验证规则
 * @USER: liujia
 * @date 2023/5/11 9:09
 */
@Configuration
@Slf4j
@Order(1)
public class StartApplicationBeforeValidate implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Resource
    private AssistantService assistantService;

    @Resource
    private BvAudioPlayService bvAudioPlayService;

    @Resource
    private BvConfigService bvConfigService;

    @Resource
    private BvModelService bvModelService;

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;

        log.error("服务启动，准备初始化模型...");
        try {

            // 先尝试停止可能正在运行的模型
            assistantService.shutDownModel();

            // 等待一段时间确保模型完全停止
            ThreadUtil.sleep(5000);

            ConfigDto config = bvConfigService.getConfig();

            List<String> modelList = Arrays.asList(
                    config.getModelSetting().getAnchor(),
                    config.getModelSetting().getAssistant()
            );

            // 解密模型
            bvAudioPlayService.decryptModel(modelList);

            // 切换模型
//            bvModelService.switchModel(PlayerType.ANCHOR, config.getModelSetting().getAnchor());
//            bvModelService.switchModel(PlayerType.ASSISTANT, config.getModelSetting().getAssistant());

            // 启动模型
            try {
                assistantService.startModel();
            } catch (Exception e) {
                log.error("模型启动失败", e);
                throw new BusException("模型启动失败: " + e.getMessage());
            }

            log.error("模型初始化完成");
        } catch (Exception e) {
            log.error("模型初始化失败：", e);
        }


    }

}
